package com.zqwh.yj.sdk.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

/**
 * Created by eason.yang on 2018/9/10.
 */

public class SignUtils {
    public static String getNonce() {
        StringBuffer fm = new StringBuffer();
        Random r = new Random();
        for (int i = 0; i < 9; i++) {
            fm.append(r.nextInt(9));
        }
        return fm.toString();
    }

    public static String getTimestamp() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String time = dateFormat.format(date);
        return time;
    }

    public static String getSign(String token, String timestamp, String nonce) {
        String sign = null;
        String[] arr = {token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            buff.append(arr[i]);
        }
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        digest.update(buff.toString().getBytes());
        sign = byte2hex(digest.digest());
        return sign;
    }

    public static String byte2hex(byte[] b) {
        StringBuilder sbDes = new StringBuilder();
        String tmp = null;
        for (int i = 0; i < b.length; i++) {
            tmp = (Integer.toHexString(b[i] & 0xFF));
            if (tmp.length() == 1) {
                sbDes.append("0");
            }
            sbDes.append(tmp);
        }
        return sbDes.toString();
    }
}
